<template>
  <div class="course-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('course.title') }}</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text" 
          icon="el-icon-plus" 
          @click="handleAdd"
          v-if="isTeacher || isAdmin">
          {{ $t('course.add') }}
        </el-button>
      </div>
      
      <!-- 搜索条件 -->
      <div class="search-container">
        <el-form :inline="false" :model="searchForm" class="search-form" size="small">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item :label="$t('course.name')">
                <el-input v-model="searchForm.name" :placeholder="$t('common.pleaseEnter') + ' ' + $t('course.name')" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item :label="$t('course.teacher')">
                <el-input v-model="searchForm.teacherName" :placeholder="$t('common.pleaseEnter') + ' ' + $t('course.teacherName')" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item :label="$t('course.location')">
                <el-input v-model="searchForm.location" :placeholder="$t('common.pleaseEnter') + ' ' + $t('course.location')" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item :label="$t('course.schedule')">
                <el-date-picker
                  v-model="searchForm.courseDate"
                  type="date"
                  :placeholder="$t('common.pleaseSelect') + ' ' + $t('common.date')"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  clearable>
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" class="search-buttons">
              <el-form-item>
                <el-button type="primary" @click="searchCourses">{{ $t('common.search') }}</el-button>
                <el-button @click="resetSearch">{{ $t('common.reset') }}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <div class="course-list">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in tableData" :key="item.id" class="course-item">
            <el-card shadow="hover" class="course-card">
              <div class="course-header">
                <h3 class="course-name">{{ item.name }}</h3>
                <el-tag size="small" type="primary">{{ item.selectedNum }}/{{ item.maxNum }}{{ $t('course.students') }}</el-tag>
              </div>
              
              <div class="course-info">
                <p><i class="el-icon-user"></i> {{ $t('course.teacher') }}：{{ item.teacherName }}</p>
                <p><i class="el-icon-date"></i> {{ $t('course.schedule') }}：{{ formatDate(item.courseDate) }}</p>
                <p><i class="el-icon-time"></i> {{ $t('course.period') }}：{{ item.startTime }} - {{ item.endTime }}</p>
                <p><i class="el-icon-location"></i> {{ $t('course.location') }}：{{ item.location }}</p>
                <p class="course-desc"><i class="el-icon-document"></i> {{ $t('course.description') }}：{{ item.info || $t('course.noDescription') }}</p>
              </div>
              
              <div class="course-actions">
                <el-button-group v-if="isTeacher || isAdmin">
                  <el-button type="primary" size="mini" @click="handleEdit(item)">
                    <i class="el-icon-edit"></i> {{ $t('common.edit') }}
                  </el-button>
                  <el-button type="danger" size="mini" @click="handleDelete(item)">
                    <i class="el-icon-delete"></i> {{ $t('common.delete') }}
                  </el-button>
                  <el-button type="warning" size="mini" @click="handleStudentList(item)">
                    <i class="el-icon-user"></i> {{ $t('course.studentList') }}
                  </el-button>
                </el-button-group>
                
                <el-button-group v-else>
                  <el-button 
                    v-if="!item.isSelected" 
                    type="success" 
                    size="mini" 
                    @click="handleSelect(item)"
                    :disabled="item.selectedNum >= item.maxNum">
                    <i class="el-icon-plus"></i> {{ $t('course.select') }}
                  </el-button>
                  <el-button 
                    v-else 
                    type="danger" 
                    size="mini" 
                    @click="handleUnselect(item)">
                    <i class="el-icon-minus"></i> {{ $t('course.unselect') }}
                  </el-button>
                </el-button-group>
                
                <el-button type="info" size="mini" @click="handleView(item)">
                  <i class="el-icon-view"></i> {{ $t('common.view') }}
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 空状态 -->
        <el-empty v-if="tableData.length === 0" description="暂无课程数据"></el-empty>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[12, 24, 36, 48]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>
      </div>
    </el-card>
    
    <!-- 编辑/添加对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="任课教师" prop="userId" v-if="isAdmin">
          <el-select v-model="form.userId" placeholder="请选择教师">
            <el-option 
              v-for="teacher in teachers" 
              :key="teacher.id" 
              :label="teacher.name" 
              :value="teacher.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程时间" required>
          <el-col :span="11">
            <el-form-item prop="startDate">
              <el-date-picker
                v-model="form.startDate"
                type="date"
                placeholder="开始日期"
                value-format="yyyy-MM-dd"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">至</el-col>
          <el-col :span="11">
            <el-form-item prop="endDate">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="上课时间" required>
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-time-picker
                v-model="form.startTime"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                placeholder="开始时间"
                style="width: 100%">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">至</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-time-picker
                v-model="form.endTime"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                placeholder="结束时间"
                style="width: 100%">
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="上课地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入上课地点"></el-input>
        </el-form-item>
        <el-form-item label="地理位置">
          <el-col :span="11">
            <el-form-item prop="locationLatitude">
              <el-input v-model.number="form.locationLatitude" placeholder="纬度"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">-</el-col>
          <el-col :span="11">
            <el-form-item prop="locationLongitude">
              <el-input v-model.number="form.locationLongitude" placeholder="经度"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="最大人数" prop="maxNum">
          <el-input-number v-model="form.maxNum" :min="1" :max="200"></el-input-number>
        </el-form-item>
        <el-form-item label="课程简介" prop="info">
          <el-input type="textarea" v-model="form.info" :rows="3" placeholder="请输入课程简介"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 选课确认对话框 -->
    <el-dialog title="选课确认" :visible.sync="selectDialogVisible" width="400px">
      <div>
        <p>确定要选择课程 <strong>{{ selectCourse.name }}</strong> 吗？</p>
        <p>任课教师: {{ selectCourse.teacherName }}</p>
        <p>上课时间: {{ formatDate(selectCourse.courseDate) }} {{ selectCourse.startTime }} - {{ selectCourse.endTime }}</p>
        <p>上课地点: {{ selectCourse.location }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelect" :loading="selectLoading">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 课程详情对话框 -->
    <el-dialog title="课程详情" :visible.sync="detailDialogVisible" width="600px">
      <div v-if="currentCourse">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="课程名称">{{ currentCourse.name }}</el-descriptions-item>
          <el-descriptions-item label="任课教师">{{ currentCourse.teacherName }}</el-descriptions-item>
          <el-descriptions-item label="上课时间">{{ formatDate(currentCourse.courseDate) }} {{ currentCourse.startTime }} - {{ currentCourse.endTime }}</el-descriptions-item>
          <el-descriptions-item label="上课地点">{{ currentCourse.location }}</el-descriptions-item>
          <el-descriptions-item label="选课情况">{{ currentCourse.selectedNum }}/{{ currentCourse.maxNum }}</el-descriptions-item>
          <el-descriptions-item label="课程简介">{{ currentCourse.info }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
    
    <!-- 学生列表对话框 -->
    <el-dialog title="课程学生列表" :visible.sync="studentDialogVisible" width="800px" custom-class="wide-dialog">
      <div v-if="currentCourse">
        <div class="student-header">
          <h4>{{ currentCourse.name }} - {{ $t('course.studentList') }}</h4>
          <div class="student-count">
            已选人数：{{ currentCourse.selectedNum }}/{{ currentCourse.maxNum }}
          </div>
        </div>
        
        <!-- 学生列表 -->
        <div v-loading="studentLoading">
          <!-- 表格形式显示学生列表 -->
          <el-table :data="studentList" border style="width: 100%">
            <el-table-column prop="id" label="学号" width="100"></el-table-column>
            <el-table-column prop="name" label="姓名" width="120"></el-table-column>
            <el-table-column prop="groupName" label="班级" width="150"></el-table-column>
            <el-table-column prop="telephone" label="电话" width="150"></el-table-column>
            <el-table-column prop="mail" label="邮箱"></el-table-column>
            <el-table-column label="操作" width="120" v-if="(isTeacher || isAdmin) && !isMobile">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="handleRemoveStudent(scope.row)">
                  <i class="el-icon-delete"></i> {{ $t('common.remove') }}
                </el-button>
              </template>
            </el-table-column>
            <!-- 移动端操作列 -->
            <el-table-column label="操作" width="95" fixed="right" v-if="(isTeacher || isAdmin) && isMobile">
              <template slot-scope="scope">
                <el-popover
                  placement="left"
                  width="120"
                  trigger="click">
                  <div class="mobile-operation-buttons">
                    <el-button type="danger" size="mini" @click="handleRemoveStudent(scope.row)">
                      <i class="el-icon-delete"></i> {{ $t('common.remove') }}
                    </el-button>
                  </div>
                  <el-button slot="reference" type="primary" size="mini">
                    {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 空状态 -->
          <el-empty v-if="studentList.length === 0" description="暂无学生数据"></el-empty>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleStudentSizeChange"
              @current-change="handleStudentCurrentChange"
              :current-page="studentPagination.currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="studentPagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="studentPagination.total">
            </el-pagination>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Course",
  data() {
    return {
      userInfo: JSON.parse(sessionStorage.getItem("userInfo")),
      isTeacher: false,
      isAdmin: false,
      loading: false,
      submitLoading: false,
      selectLoading: false,
      
      // 搜索表单
      searchForm: {
        name: '',
        userId: '',
        current: 1,
        size: 12
      },
      
      // 表格数据
      tableData: [],
      
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      
      // 对话框
      dialogVisible: false,
      dialogTitle: '添加课程',
      form: this.getDefaultForm(),
      rules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请选择任课教师', trigger: 'change' }
        ],
        startDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入上课地点', trigger: 'blur' }
        ],
        maxNum: [
          { required: true, message: '请输入最大人数', trigger: 'blur' },
          { type: 'number', min: 1, max: 200, message: '人数范围在1-200之间', trigger: 'blur' }
        ]
      },
      
      // 教师列表
      teachers: [],
      
      // 选课对话框
      selectDialogVisible: false,
      selectCourse: {},
      
      // 退课对话框
      unselectDialogVisible: false,
      unselectCourse: {},
      unselectLoading: false,
      
      // 详情对话框
      detailDialogVisible: false,
      currentCourse: null,
      
      // 学生列表对话框
      studentDialogVisible: false,
      studentList: [],
      studentLoading: false,
      
      // 学生列表分页
      studentPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      isMobile: false,
      screenWidth: document.body.clientWidth,
    }
  },
  created() {
    this.checkUserRole();
    this.initData();
    this.checkScreenSize();
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
    this.checkScreenSize();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    checkUserRole() {
      // 检查用户角色
      if (this.userInfo && this.userInfo.roleName) {
        this.isTeacher = this.userInfo.roleName.includes('teacher');
        this.isAdmin = this.userInfo.roleName.includes('admin');
      }
    },
    initData() {
      // 获取课程列表
      this.searchCourses();
      
      // 如果是管理员，获取教师列表
      if (this.isAdmin) {
        this.getTeachers();
      }
    },
    getDefaultForm() {
      return {
        id: null,
        name: '',
        userId: this.isTeacher ? this.userInfo.userId : null,
        startDate: '',
        endDate: '',
        startTime: '',
        endTime: '',
        location: '',
        locationLatitude: null,
        locationLongitude: null,
        maxNum: 50,
        selectedNum: 0,
        info: ''
      };
    },
    getTeachers() {
      // 获取教师列表
      this.$axios.get('/user/list', {
        params: {
          currentPage: 1,
          pageSize: 100,
          roleType: 'teacher'
        }
      }).then(res => {
        if (res.code === 200) {
          this.teachers = res.data.records || [];
          // 获取到教师列表后重新加载课程列表，以显示教师名称
          this.searchCourses();
        }
      }).catch(err => {
        console.error('获取教师列表失败', err);
        this.$message.error('获取教师列表失败');
      });
    },
    searchCourses() {
      this.loading = true;
      
      // 构建请求参数
      const params = {
        ...this.searchForm,
        current: this.pagination.currentPage,
        size: this.pagination.pageSize
      };
      
      // 如果是教师，只查询自己的课程
      if (this.isTeacher && !this.isAdmin) {
        params.userId = this.userInfo.userId;
      }
      
      this.$axios.get('/course/page', { params }).then(res => {
        if (res.code === 200) {
          const data = res.data;
          this.tableData = data.records || [];
          this.pagination.total = data.total || 0;
          
          // 处理教师名称
          if (this.teachers.length > 0) {
            this.tableData.forEach(item => {
              const teacher = this.teachers.find(t => t.id === item.userId);
              if (teacher) {
                item.teacherName = teacher.name;
              }
            });
          }
          
          // 如果是学生，检查每个课程是否已选
          if (!this.isTeacher && !this.isAdmin && this.userInfo && this.userInfo.userId) {
            //console.log('用户是学生，检查已选课程');
            this.checkSelectedCourses();
          } else {
            //console.log('用户不是学生或用户信息不完整，跳过检查已选课程');
          }
        } else {
          this.$message.error(res.data.msg || '获取课程列表失败');
        }
      }).catch(err => {
        console.error('获取课程列表失败', err);
        this.$message.error('获取课程列表失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    resetSearch() {
      this.searchForm = {
        name: '',
        userId: '',
        current: 1,
        size: 12
      };
      this.pagination.currentPage = 1;
      this.searchCourses();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.searchForm.size = val;
      this.searchCourses();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.searchForm.current = val;
      this.searchCourses();
    },
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleDateString();
    },
    handleAdd() {
      this.dialogTitle = '添加课程';
      this.form = this.getDefaultForm();
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑课程';
      this.form = { ...row };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('确认删除该课程吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/course/delete/${row.id}`).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.searchCourses();
          } else {
            this.$message.error(res.data.msg || '删除失败');
          }
        }).catch(err => {
          console.error('删除课程失败', err);
          this.$message.error('删除课程失败');
        });
      }).catch(() => {});
    },
    handleSelect(row) {
      this.selectCourse = row;
      this.selectDialogVisible = true;
    },
    confirmSelect() {
      this.selectLoading = true;
      // 使用正确的选课API接口
      const selectedCourseDTO = {
        courseId: this.selectCourse.id,
        userId: this.userInfo.userId
      };
      
      this.$axios.post('/selectedCourse/select', selectedCourseDTO).then(res => {
        if (res.code === 200) {
          this.$message.success('选课成功');
          this.selectDialogVisible = false;
          this.searchCourses();
        } else {
          this.$message.error(res.data.msg || '选课失败');
        }
      }).catch(err => {
        console.error('选课失败', err);
        this.$message.error('选课失败');
      }).finally(() => {
        this.selectLoading = false;
      });
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.form.startTime || !this.form.endTime) {
            this.$message.warning('请选择上课时间');
            return;
          }
          
          // 验证结束时间是否大于开始时间
          if (this.form.startTime >= this.form.endTime) {
            this.$message.warning('结束时间必须大于开始时间');
            return;
          }

          // 验证结束日期是否大于开始日期
          if (this.form.startDate >= this.form.endDate) {
            this.$message.warning('结束日期必须大于开始日期');
            return;
          }
          
          this.submitLoading = true;
          const url = this.form.id ? '/course/update' : '/course/create';
          const method = this.form.id ? 'put' : 'post';
          
          this.$axios[method](url, this.form).then(res => {
            if (res.code === 200) {
              this.$message.success(this.form.id ? '编辑成功' : '添加成功');
              this.dialogVisible = false;
              this.searchCourses();
            } else {
              this.$message.error(res.data.msg || (this.form.id ? '编辑失败' : '添加失败'));
            }
          }).catch(err => {
            console.error(this.form.id ? '编辑课程失败' : '添加课程失败', err);
            this.$message.error(this.form.id ? '编辑课程失败' : '添加课程失败');
          }).finally(() => {
            this.submitLoading = false;
          });
        } else {
          return false;
        }
      });
    },
    handleView(row) {
      this.currentCourse = row;
      this.detailDialogVisible = true;
    },
    handleStudentList(row) {
      this.currentCourse = row;
      this.studentDialogVisible = true;
      // 重置分页
      this.studentPagination.currentPage = 1;
      this.getStudentList();
    },
    getStudentList() {
      if (!this.currentCourse) return;
      
      this.studentLoading = true;
      // 获取课程学生列表，使用正确的API路径
      this.$axios.get(`/selectedCourse/course/students/${this.currentCourse.id}`, {
        params: {
          current: this.studentPagination.currentPage,
          size: this.studentPagination.pageSize
        }
      }).then(res => {
        if (res.code === 200) {
          // 直接使用返回的数据，不再尝试获取records
          const students = res.data || [];
          this.studentPagination.total = students.length || 0;
          
          // 获取班级信息
          const groupIds = [...new Set(students.map(s => s.groupId).filter(id => id))];
          if (groupIds.length > 0) {
            this.$axios.get('/group/list').then(groupRes => {
              if (groupres.code === 200) {
                const groups = groupres.data || [];
                // 将班级信息添加到学生数据中
                this.studentList = students.map(student => {
                  const group = groups.find(g => g.id === student.groupId);
                  return {
                    ...student,
                    groupName: group ? group.name : '未分配班级'
                  };
                });
              }
            }).catch(err => {
              console.error('获取班级信息失败', err);
              this.studentList = students;
            });
          } else {
            this.studentList = students;
          }
        } else {
          this.$message.error(res.data.msg || '获取学生列表失败');
        }
      }).catch(err => {
        console.error('获取学生列表失败', err);
        this.$message.error('获取学生列表失败');
      }).finally(() => {
        this.studentLoading = false;
      });
    },
    handleStudentSizeChange(val) {
      this.studentPagination.pageSize = val;
      this.getStudentList();
    },
    handleStudentCurrentChange(val) {
      this.studentPagination.currentPage = val;
      this.getStudentList();
    },
    handleRemoveStudent(student) {
      this.$confirm(`确定要将学生 ${student.name} 从课程中移除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/course/drop/${this.currentCourse.id}`, {
          params: { userId: student.id }
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('移除成功');
            this.getStudentList();
            // 更新课程信息
            this.searchCourses();
          } else {
            this.$message.error(res.data.msg || '移除失败');
          }
        }).catch(err => {
          console.error('移除学生失败', err);
          this.$message.error('移除学生失败');
        });
      }).catch(() => {});
    },
    // 检查学生已选课程
    checkSelectedCourses() {
      if (!this.userInfo || !this.userInfo.userId || this.tableData.length === 0) {
        console.warn('无法检查已选课程：用户信息不完整或课程列表为空');
        return;
      }
      
      //console.log('检查已选课程，用户ID:', this.userInfo.userId);
      
      const promises = this.tableData.map(course => {
        return this.$axios.get('/selectedCourse/isSelected', {
          params: {
            courseId: course.id,
            userId: this.userInfo.userId
          }
        }).then(res => {
          if (res.code === 200) {
            course.isSelected = res.data;
            //console.log(`课程 ${course.id} 是否已选: ${course.isSelected}`);
          } else {
            console.warn(`获取课程 ${course.id} 选课状态失败:`, res.data.msg);
            course.isSelected = false;
          }
          return course;
        }).catch(err => {
          console.error(`获取课程 ${course.id} 选课状态出错:`, err);
          course.isSelected = false;
          return course;
        });
      });
      
      Promise.all(promises).then(updatedCourses => {
        this.tableData = updatedCourses;
      }).catch(err => {
        console.error('检查已选课程出错:', err);
      });
    },
    handleUnselect(row) {
      this.unselectCourse = row;
      this.$confirm(`确定要退出课程 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.confirmUnselect();
      }).catch(() => {});
    },
    confirmUnselect() {
      this.unselectLoading = true;
      const selectedCourseDTO = {
        courseId: this.unselectCourse.id,
        userId: this.userInfo.userId
      };
      
      this.$axios.post('/selectedCourse/unselect', selectedCourseDTO).then(res => {
        if (res.code === 200) {
          this.$message.success('退课成功');
          this.searchCourses();
        } else {
          this.$message.error(res.data.msg || '退课失败');
        }
      }).catch(err => {
        console.error('退课失败', err);
        this.$message.error('退课失败');
      }).finally(() => {
        this.unselectLoading = false;
      });
    },
    handleResize() {
      this.screenWidth = document.body.clientWidth;
      this.checkScreenSize();
    },
    checkScreenSize() {
      this.isMobile = this.screenWidth < 768;
    },
  }
}
</script>

<style lang="scss" scoped>
.course-container {
  padding: 10px;
}

@media screen and (min-width: 768px) {
  .course-container {
    padding: 20px;
  }
}

.search-container {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.search-buttons {
  text-align: right;
  margin-top: 10px;
}

@media screen and (max-width: 767px) {
  .search-buttons {
    text-align: center;
  }
  
  .el-form-item {
    margin-bottom: 10px;
  }
  
  .el-button + .el-button {
    margin-left: 5px;
  }
}

.course-list {
  margin-top: 20px;
}

.course-item {
  margin-bottom: 20px;
}

.course-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-bottom: 10px;
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.course-name {
  margin: 0;
  font-size: 16px;
  color: #303133;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.course-info {
  flex: 1;
  min-height: 150px;
  display: flex;
  flex-direction: column;
}

.course-info p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.course-info i {
  margin-right: 5px;
  width: 16px;
  color: #909399;
}

.course-desc {
  margin-top: 10px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.course-actions {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 10px;
}

.el-button-group {
  display: flex;
//   gap: 5px;
  margin-bottom: 5px;
  width: 100%;
}

.el-button-group .el-button {
  flex: 1;
  margin-left: 0 !important;
}

.course-actions .el-button {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.course-actions .el-button i {
  margin-right: 5px;
}

@media screen and (min-width: 1200px) {
  .course-card {
    min-height: 320px;
  }
}

@media screen and (max-width: 767px) {
  .course-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .el-button-group {
    margin-bottom: 5px;
  }
  
  .el-button {
    width: 100%;
  }
}

.pagination-container {
  margin-top: 30px;
  text-align: center;
}

@media screen and (min-width: 768px) {
  .pagination-container {
    text-align: right;
  }
}

.el-dialog {
  border-radius: 8px;
  margin: 5vh auto !important;
  width: 95% !important;
}

@media screen and (min-width: 768px) {
  .el-dialog {
    width: 600px !important;
  }
  
  .el-dialog.wide-dialog {
    width: 800px !important;
  }
}

.el-dialog__header {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__body {
  padding: 20px 15px;
}

@media screen and (min-width: 768px) {
  .el-dialog__header {
    padding: 20px;
  }
  
  .el-dialog__body {
    padding: 30px 20px;
  }
}

.el-descriptions {
  margin: 20px 0;
}

.el-descriptions-item__label {
  width: 100px;
  color: #606266;
}

@media screen and (min-width: 768px) {
  .el-descriptions-item__label {
    width: 120px;
  }
}

.el-form-item {
  margin-bottom: 18px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.student-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;

  h4 {
    margin: 0;
    font-size: 16px;
    color: #303133;
  }

  .student-count {
    font-size: 14px;
    color: #606266;
  }
}

.student-item {
  margin-bottom: 20px;
}

.student-card {
  height: 100%;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }

  .student-info {
    display: flex;
    align-items: flex-start;
    padding: 10px;
  }

  .student-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;

    i {
      font-size: 30px;
      color: #909399;
    }
  }

  .student-detail {
    flex: 1;

    h4 {
      margin: 0 0 10px;
      font-size: 16px;
      color: #303133;
    }

    p {
      margin: 5px 0;
      font-size: 14px;
      color: #606266;

      i {
        margin-right: 5px;
        color: #909399;
      }
    }
  }

  .student-actions {
    padding: 10px;
    border-top: 1px solid #ebeef5;
    text-align: right;
  }
}

.wide-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

@media screen and (max-width: 768px) {
  .student-card {
    .student-info {
      flex-direction: column;
      align-items: center;
      text-align: center;
    }

    .student-avatar {
      margin-right: 0;
      margin-bottom: 15px;
    }

    .student-actions {
      .el-button {
        width: 100%;
      }
    }
  }
}

.mobile-operation-buttons {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.mobile-operation-buttons .el-button {
  margin-left: 0;
  margin-bottom: 8px;
  width: 100%;
  text-align: left;
}

.mobile-operation-buttons .el-button:last-child {
  margin-bottom: 0;
}

@media screen and (max-width: 768px) {
  .el-table {
    width: 100%;
    font-size: 12px;
  }
  
  .el-button {
    padding: 7px 10px;
    font-size: 12px;
  }
}
</style> 